package com.cndw.kungfu.model.main;

import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

import org.springframework.stereotype.Component;

import com.cndw.kungfu.core.SimpleThreadFactory;

/**
 * 定时器管理类 暂时采用封装方式,日后看需要
 * 
 * @author fantadust
 * @date 2011-4-28 上午11:28:48
 */
@Component
public class TimerServer {

	private final ScheduledExecutorService scheduExec;

	public TimerServer() {
		scheduExec = Executors.newScheduledThreadPool(50, new SimpleThreadFactory("TimeServer"));
	}

	/**
	 * 获取服务器定时器,暂时内部封装
	 * 
	 * @return
	 */
	public ScheduledExecutorService getScheduledExecutor() {
		return scheduExec;

	}

	/**
	 * 0延迟立即执行
	 * 
	 * @param command
	 */
	public void execute(Runnable command) {
		getScheduledExecutor().execute(command);
	}

	/**
	 * 执行一个延迟事件毫秒
	 * 
	 * @param command
	 * @param delay
	 * @return
	 */
	public ScheduledFuture<?> scheduleMilliSeconds(Runnable command, long delay) {
		return getScheduledExecutor().schedule(command, delay, TimeUnit.MILLISECONDS);
	}

	/**
	 * 执行个任务秒
	 * 
	 * @param command
	 * @param delay
	 * @return
	 */
	public ScheduledFuture<?> scheduleSeconds(Runnable command, long delay) {
		return getScheduledExecutor().schedule(command, delay, TimeUnit.SECONDS);
	}

	/**
	 * 自定义时间执行
	 * 
	 * @param command
	 * @param delay
	 * @param unit
	 * @return
	 */
	public ScheduledFuture<?> schedule(Runnable command, long delay, TimeUnit unit) {
		return getScheduledExecutor().schedule(command, delay, unit);
	}

	/**
	 * 创建并执行一个在给定初始延迟后首次启用的定期操作，后续操作具有给定的周期
	 * 
	 * @param command
	 * @param delay
	 * @return
	 */
	public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, int delay) {

		return getScheduledExecutor().scheduleAtFixedRate(command, delay, delay, TimeUnit.SECONDS);
	}
	/**
	 * 创建并执行一个在给定初始延迟后首次启用的定期操作，后续操作具有给定的周期
	 * @param command
	 * @param initialDelay
	 * @param delay
	 * @return
	 */
	public ScheduledFuture<?> scheduleAtFixedRate(Runnable command, int initialDelay, int delay) {

		return getScheduledExecutor().scheduleAtFixedRate(command, initialDelay, delay, TimeUnit.SECONDS);
	}

	/**
	 * 运行完成和下次开始固定间隔
	 * 
	 * @param command
	 * @param delay
	 * @return
	 */
	public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, int delay) {
		return getScheduledExecutor().scheduleWithFixedDelay(command, delay, delay, TimeUnit.SECONDS);
	}

	public ScheduledFuture<?> scheduleWithFixedDelay(Runnable command, int initialDelay, int delay) {
		return getScheduledExecutor().scheduleWithFixedDelay(command, initialDelay, delay, TimeUnit.SECONDS);
	}
	
	public void shutdown(){
		//getScheduledExecutor().shutdown();
	}

}
